package com.aim.common.aop;

import com.aim.common.annotion.BizLog;
import com.aim.common.handler.log.LogManager;
import com.aim.common.handler.log.LogObjectHolder;
import com.aim.common.handler.log.factory.LogTaskFactory;
import com.aim.common.util.BeanUtils;
import com.aim.common.util.WebUtil;
import com.aim.config.shiro.ShiroKit;
import com.aim.config.shiro.ShiroUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @AUTO 日志记录
 * @Author AIM
 * @DATE 2019/4/25
 */
@Aspect
@Component
public class LogAop {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "@annotation(com.aim.common.annotion.BizLog)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
        //先执行业务
        Object result = point.proceed();
        try {
            handle(point);
        } catch (Exception e) {
            log.error("日志记录出错!", e);
        }
        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {
        //获取拦截的方法名
        Signature sig = point.getSignature();
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        MethodSignature msig = (MethodSignature) sig;
        Object objs = point.getTarget();
        Method currentMethod = objs.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        String methodName = currentMethod.getName();

        //如果当前用户未登录，不做日志
        ShiroUser user = ShiroKit.getUser();
        if (null == user) {
            return;
        }

        //获取拦截方法的参数
        String className = point.getTarget().getClass().getName();
        Object[] params = point.getArgs();

        //获取操作名称
        BizLog annotation = currentMethod.getAnnotation(BizLog.class);
        String bussinessName = annotation.value(); // 业务的名称
        String key = annotation.key(); // 唯一标识
        Class dictClass = annotation.dict(); // 获取字典类

        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(param);
            sb.append(" & ");
        }

        //如果涉及到修改,比对变化
        String msg = "";
        if (bussinessName.contains("修改") || bussinessName.contains("保存")) {
            Object source = LogObjectHolder.me().get();
            Map<String, Object> parameters = WebUtil.getRequestParameters();
            Object target = BeanUtils.map2Java(source.getClass(), parameters);
            msg = "操作业务" + bussinessName + "不一致参数：" + BeanUtils.compareFields(source, target, null).toString();
        } else {
            Map<String, Object> parameters = WebUtil.getRequestParameters();
            msg = "操作业务" + bussinessName + "参数：" + parameters.toString();
        }

        LogManager.me().execLog(LogTaskFactory.bizLog(user.getUserId(), bussinessName, className, methodName, msg));
    }
}
